package com.codefish.codefishseckill.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Cookie操作类
 *
 * @author codefish
 * @version 1.0
 * @date 2022/04/10 下午 10:08
 */
public class CookieUtil {

    public static final String USER_INFO_KEY = "userToken";
    public static final int DAY = 24*60*60;
    public static final int HOUR = 60*60;
    public static final int MINUTE = 60;


    /**
     * 从请求中获取cookie
     *
     * @param request request请求
     * @param key     cookie的key
     * @return cookie的value
     */
    public static String getValueByKey(HttpServletRequest request, String key) {
        String val = null;
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            return val;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(key)) {
                val = cookie.getValue();
                break;
            }
        }
        return val;
    }

    /**
     * 向response中添加cookie
     *
     * @param response   response对象
     * @param key        cookie的key
     * @param value      cookie的value
     * @param expireTime cookie的过期时间，单位s
     * @param path       cookie的url路径
     */
    public static void setCookie(HttpServletResponse response, String key, String value, int expireTime, String path) {
        Cookie cookie = new Cookie(key, value);
        cookie.setPath(path);
        cookie.setMaxAge(expireTime);
        response.addCookie(cookie);
    }
}
